#include "mselector.h"

#include <QGraphicsSceneMouseEvent>
#include <QCursor>
#include <iostream>

MSelector::MSelector(QGraphicsItem *parent) :
    QGraphicsWidget(parent)
{
    sel = new MSelection(this);
    sel->setPos(0, 0);
    sel->updateGeometry(0, 0, -1, -1);
    setGeometry(0, 0, 1000, 1000);
    tm = new QTimer();
    tm->setInterval(20);
    tm->setSingleShot(false);
    connect(tm, SIGNAL(timeout()), this, SLOT(timer()));

    tm->start();

}

void MSelector::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    start_x = event->pos().x();
    start_y = event->pos().y();
    is_down = true;
    event->accept();

}

void MSelector::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (is_down)
    {
        end_x = event->pos().x();
        end_y = event->pos().y();
        sel->updateGeometry(std::min(start_x, end_x), std::min(start_y, end_y),
                            std::max(start_x, end_x), std::max(start_y, end_y));
        update();
        emit newSelection(std::min(start_x, end_x), std::min(start_y, end_y),
                          std::max(start_x, end_x), std::max(start_y, end_y));
    }
    event->accept();

}

void MSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    end_x = event->pos().x();
    end_y = event->pos().y();

    emit newSelection(std::min(start_x, end_x), std::min(start_y, end_y),
                      std::max(start_x, end_x), std::max(start_y, end_y));
    is_down = false;
    sel->updateGeometry(0, 0, -1, -1);
    update();
    event->accept();

    emit endSelection();
}


void MSelector::timer()
{
    if (!is_down)
    {
        QPointF p = QCursor::pos();
        emit moveOver(p.x(), p.y());
    }
}
